package com.mylock;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author:wesley
 */
public class MyAbstractLock implements Watcher {

    private ZooKeeper zk;

    private CountDownLatch cd = new CountDownLatch(1);


    public ZooKeeper connect(String ipAddress , int sessionTime){
        try {
            zk = new ZooKeeper(ipAddress,sessionTime,this);
            cd.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return zk;
    }



    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("ZK连接OK");
            cd.countDown();
        }
    }
}
